package com.Policing.Okhttps;

import android.content.Context;
import org.json.JSONException;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyOkHttp {
    private OkHttpClient okHttpClient;
    private Context context;

    public MyOkHttp(Context context) {
        this.context = context;
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(500, TimeUnit.SECONDS).build();
    }

    /**
     * get异步请求
     *
     * @param url            请求地址
     * @param requestMessage 调用自定义内部接口
     */
    public void get(String url, final requestMessage requestMessage) {
        final Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requestMessage.requestFail();
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                try {
                    requestMessage.requestSuccess(response);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * post异步请求
     *
     * @param url            请求地址
     * @param param          请求参数
     * @param requestMessage 调用内部自定义接口
     */
    public  void post(String url, Map<String, String> param, final requestMessage requestMessage) {
        FormBody.Builder body = new FormBody.Builder();
        if (param != null) {
            for (Map.Entry<String, String> data : param.entrySet()) {
                body.add(data.getKey(), data.getValue());
            }
        }
        final Request request = new Request.Builder()
                                            .post(body.build())
                                            .url(url)
                                            .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requestMessage.requestFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    requestMessage.requestSuccess(response);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 自定义请求失败与成功接口
     */
    public interface requestMessage {
        void requestFail();
        void requestSuccess(Response response) throws IOException, JSONException;
    }


}
